package cn.itcast.dao.refactor;

import cn.itcast.dao.DaoException;
import cn.itcast.dao.RowMapper;
import utils.JdbcUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class AbstractDaoOptimization {

    public void updateUser(String sql, Object[] obj) {
        // 初始化
        Connection conn = null;
        PreparedStatement ps = null;

        try {
            conn = JdbcUtils.getConnection();

            ps = conn.prepareStatement(sql);
            for (int i=0; i<obj.length; i++) {
                ps.setObject(i+1, obj[i]);
            }
            ps.executeUpdate();

        } catch (SQLException e) {
            throw new DaoException(e);
        }finally {
            JdbcUtils.free(ps, conn, null);
        }
    }

    public Object findUser(String sql, int id, RowMapper rowMapper) {
        // 初始化
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            conn = JdbcUtils.getConnection();

            ps = conn.prepareStatement(sql);
            ps.setObject(1, id);

            rs = ps.executeQuery();
            while (rs.next()) {
                return rowMapper.rowMapper(rs);
            }

        } catch (SQLException e) {
            throw new DaoException(e);
        }finally {
            JdbcUtils.free(ps, conn, null);
        }
        return null;
    }
}
